define([
    "dojo/_base/declare",
    "gistech/widgets/baseWidget/BaseWidget",
    "dojo/text!./templates/Template.html",
    "dojo/_base/lang",
    "dojo/dom-style",
    "dojo/dom-construct",
    "dojo/on",
    "dojo/_base/connect",
    "gistech/widgets/gaoDeLayer/GaoDeBaseMapLayer",
    ],
    function(declare,BaseWidget,template,lang,style,domConstruct,on,eventconnect,GaoDeBaseMapLayer){
		return declare([BaseWidget],{
		    templateString:template,
		    alignNode:null,
	        mapInfos:null,//底图信息集合
	        imagesLayerIds:[],
	        num:0,
	        regainMap:null,
	        hideWhenClickBody:false,
	        constructor:function (args) {
				 if (args.alignNode) {
			         this.alignNode = args.alignNode;
			     }
			     if (args.close) {
			         this.close = args.close;
			     }
			     if (args.hideWhenClickBody) {
			         this.hideWhenClickBody = args.hideWhenClickBody;
			     }
			     this.regainMap=(args.map != undefined)? args.map:null;
			     this.map = (args.map != undefined)? args.map:null;
		    },
		    resetAttr:function(){
		        this.inherited(arguments);
		    },
		    postMixInProperties:function () {
	        	this.mapInfos = [
		             {
		                 name:"colorpoi",
		                 title:"Colorpoi",
		                 icon:dojo.moduleUrl("gistech.widgets.baseMap", "images/1.jpg"),
		                 url:"http://map.geoq.cn/arcgis/rest/services/ChinaOnlineCommunity/MapServer"
		             },
		            /*{
		                 name:"image",//影像地图
		                 title:"Image",
		                 icon:dojo.moduleUrl("gistech.widgets.baseMap", "images/image.png")
		                 //url:"http://map.geoq.cn/arcgis/rest/services/ChinaOnlineStreetColor/MapServer"
		             },
					 {
					    name:"amap",
					    title:"AMap",
					    icon:dojo.moduleUrl("gistech.widgets.baseMap", "images/amap.png")
					 },*/
		            /* {
		                 name:"warm",
		                 title:"Warm",
		                 icon:dojo.moduleUrl("gistech.widgets.baseMap", "images/3.jpg"),
		                 url:"http://map.geoq.cn/arcgis/rest/services/ChinaOnlineStreetWarm/MapServer"
		             },*/
		            /* {
		                 name:"cold",
		                 title:"Cold",
		                 icon:dojo.moduleUrl("gistech.widgets.baseMap", "images/4.jpg"),
		                 url:"http://map.geoq.cn/arcgis/rest/services/ChinaOnlineStreetCold/MapServer"
		             },*/
		             {
		                 name:"gray",
		                 title:"Gray",
		                 icon:dojo.moduleUrl("gistech.widgets.baseMap", "images/gray.png"),
		                 url:"http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetGray/MapServer"
		             },
		             /*{
		                 name:"English",
		                 title:"English",
		                 icon:dojo.moduleUrl("gistech.widgets.baseMap", "images/en.png"),
		                 url:"http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineCommunityENG/MapServer"
		             },*/
		            /* {
					    name:"tencentmap",
					    title:"腾讯矢量",
					    icon:dojo.moduleUrl("gistech.widgets.baseMap", "images/amap.png")
					 },*/
					 {
					    name:"tencentimagemap",
					    title:"腾讯影像",
					    icon:dojo.moduleUrl("gistech.widgets.baseMap", "images/amap.png")
					 }
		         ];
	            this.inherited(arguments);
	        },
		    postCreate:function(){
		    	//debugger
		    	var currentLayer = this.getCurrentBaseMap();
	            dojo.forEach(this.mapInfos, dojo.hitch(this, function (info, idx) {
	                var li = dojo.create("li", null, this.mapsCon);
	                var img = dojo.create("img", {"src":info.icon}, li);
	                var name = dojo.create("div", {"innerHTML":info.title, "class":"mapName"}, li);
	                dojo.connect(img, "onclick", this, dojo.hitch(this, this.onMapClick, info.name));
	                if (currentLayer.url == info.url) {
	                    dojo.addClass(img, "selected");
	                }
	            }));
	            if (this.close) {
	            	dojo.style(this.btnClose, "display", "inline-block");
	            	eventconnect.connect(this.btnClose, "onclick", this, this.closeDialog);
	            }
	            dojo.addClass(this.alignNode, "selected");//选中
	            eventconnect.connect(window, "onresize", this, this.onWindowResize);
	            dojo.place(this.domNode, dojo.body());
	            this._position();
	            this._handle = dojo.subscribe("hidePanel", this, this._hidePopup);
		        this.inherited(arguments);
		    },
		    startup:function(){
		    	this.inherited(arguments);
		    },
		    //获取当前正在使用中的底图
	        getCurrentBaseMap:function () {
	        	if(Global.maps.length>1){
	        		var activeMap=dojo.filter(Global.maps,function(item){
	            	    return item.id==Global.activeMapId;
	            	})
	            	this.map=activeMap[0];
	        	}else if(Global.maps.length==1){
	        		this.map=Global.maps[0];
	        	}else{
	        		this.map=this.regainMap;
	        	}
	        	var layerIds = this.map.layerIds;
	            var currentLayer;
	            for (var i = 0; i < layerIds.length; i++) {
	                var layerId = layerIds[i];
	                var layer = this.map.getLayer(layerId);
	                if (layer instanceof esri.layers.TiledMapServiceLayer) {
	                    for (var i = 0; i < this.mapInfos.length; i++) {
	                    	if(layer.url){
	                    		if (this.mapInfos[i].url == layer.url) {
	                    			currentLayer = layer;
	                    			return currentLayer;
	                    		}
	                    	}
	                    }
	                    if(layer._attrs && layer._attrs.name){
	                    	if(layer._attrs.name == "amap"){
		                    	 currentLayer = "amap";
		                    }else if(layer._attrs.name == "image"){
		                    	currentLayer = "image";
		                    }else if(layer._attrs.name == "tencentmap"){
		                    	currentLayer = "tencentmap";
		                    }else if(layer._attrs.name == "tencentimagemap"){
		                    	currentLayer = "tencentimagemap";
		                    }
	                    }
	                    return currentLayer;//影像图层rul为空，当前图层url不存在时，就是影像图层
	                }
	            }
	            return null;
	        },
	        getBaseMapTitle:function(){
	        	var layerIds = this.map.layerIds;
	            var currentLayer;
	            for (var i = 0; i < layerIds.length; i++) {
	                var layerId = layerIds[i];
	                var layer = this.map.getLayer(layerId);
	                if (layer instanceof esri.layers.TiledMapServiceLayer) {
	                    for (var i = 0; i < this.mapInfos.length; i++) {
	                        if (this.mapInfos[i].url == layer.url) {
	                            return this.mapInfos[i].title;
	                        }
	                    }
	                }
	            }
	            return null;
	        },
	        /**
	         * 切换地图底图
	         */
	        onMapClick:function (name, evt) {
	        	//debugger
	        	var currentLayer = this.getCurrentBaseMap();
	        	if(name == "image"){ //切换影像图
	        		if(!this.imagesLayerIds){
	        			this.imagesLayerIds=[];
	        		}
	        		if(this.imagesLayerIds.length == 0){
	        			this.handleImagesLayer(currentLayer);
	        		}/*else{
	        			return ;//如果影像图层存在返回
	        		}*/
	        	}else if(name == "amap"){//切换高德矢量图
	        		if(!this.amapsLayerIds){
	        			this.amapsLayerIds=[];
	        		}
	        		if(this.amapsLayerIds.length == 0){
	        			this.handleAmapsLayer(currentLayer);
	        		}
	        	}else if(name == "tencentmap"){
	        		if(!this.tencentLayerIds){
	        			this.tencentLayerIds=[];
	        		}
	        		if(this.tencentLayerIds.length == 0){
	        			this.handletencentLayer(currentLayer);
	        		}
	        	}else if(name == "tencentimagemap"){
//	        		if(!this.tencentImagesLayerIds){
	        			this.tencentImagesLayerIds=[];
//	        		}
	        		if(this.tencentImagesLayerIds.length == 0){
	        			this.handleTencentImagesLayer(currentLayer);
	        		}
	        	}else{
	        		this.handOtherLayer(currentLayer,name); 
	        	}
	        	
	        	this.changeSelectedStyle(evt);
	        },
	        /**
	         * 非影像地图切换
	         */
	        handOtherLayer: function(currentLayer,name) {
	        	var selectedMap = null,isCurrent = false;
        		dojo.forEach(this.mapInfos, function (info, idx) {
        			if (info.name == name) {
        				selectedMap = info;
        				return;
        			}
        		});
        		//debugger
        		//移除当前图层图层
        		if(currentLayer instanceof Object){
        			if(currentLayer.url){
            			if (selectedMap.url != currentLayer.url) {
            				this.map.removeLayer(currentLayer);
            			}else{
            				isCurrent = true;
            			}
            		}
        		}else{
        			if(currentLayer == "image"){	//移除影像图层
        				for(var i=0; i<this.imagesLayerIds.length; i++){
        					var layer = this.map.getLayer(this.imagesLayerIds[i]);
        					this.map.removeLayer(layer);
        				}
        				this.imagesLayerIds = [];
        			}else if(currentLayer == "amap"){
        				//debugger
        				for(var i=0; i<this.amapsLayerIds.length; i++){
        					var layer = this.map.getLayer(this.amapsLayerIds[i]);
        					this.map.removeLayer(layer);
        				}
        				this.amapsLayerIds = [];
        			}else if(currentLayer == "tencentmap"){
        				//debugger
        				for(var i=0; i<this.tencentLayerIds.length; i++){
        					var layer = this.map.getLayer(this.tencentLayerIds[i]);
        					this.map.removeLayer(layer);
        				}
        				this.tencentLayerIds = [];
        			}else if(currentLayer == "tencentimagemap"){
        				//debugger
        				for(var i=0; i<this.tencentImagesLayerIds.length; i++){
        					var layer = this.map.getLayer(this.tencentImagesLayerIds[i]);
        					this.map.removeLayer(layer);
        				}
        				this.tencentImagesLayerIds = [];
        			}
        		}
        		//添加新图层
        		if(!isCurrent){
        			var newBaseMap = new esri.layers.ArcGISTiledMapServiceLayer(selectedMap.url);;
        			this.map.addLayer(newBaseMap, 0);//将底图放到最底层
        		}
	        },
	        /**
	         * 影像地图切换
	         */
	        handleImagesLayer:function(currentLayer){
	        	debugger
	        	if(currentLayer instanceof Object){
	        		if(currentLayer.url){
	    				this.map.removeLayer(currentLayer);
	    			}
	        	}else{
	        		if(currentLayer == "amap"){
		        		for(var i=0 ; i<this.amapsLayerIds.length; i++){
		        			var layer = this.map.getLayer(this.amapsLayerIds[i]);
	    					this.map.removeLayer(layer);
		        		}
		        		this.amapsLayerIds=[];
		        	}else if(currentLayer == "tencentmap"){
		        		for(var i=0 ; i<this.tencentLayerIds.length; i++){
		        			var layer = this.map.getLayer(this.tencentLayerIds[i]);
	    					this.map.removeLayer(layer);
		        		}
		        		this.tencentLayerIds=[];
		        	}else if(currentLayer == "tencentimagemap"){
		        		for(var i=0 ; i<this.tencentImagesLayerIds.length; i++){
		        			var layer = this.map.getLayer(this.tencentImagesLayerIds[i]);
	    					this.map.removeLayer(layer);
		        		}
		        		this.tencentImagesLayerIds=[];
		        	}
	        	}
    			var olderlayers,newlayers ="";
    			olderlayers =  this.map.layerIds.join(" ");
    			this._addImagesLayer();//添加影像图层
    			newlayers = this.map.layerIds.join(" ");
    			//根据添加影像地图前后图层的变化，来获取图层影像id
    			this.getImagesLayerIds(olderlayers,newlayers);
	        },
	        /**
	         * 高德矢量地图切换
	         */
	        handleAmapsLayer:function(currentLayer){
	        	if(currentLayer instanceof Object){
	        		if(currentLayer.url){
	    				this.map.removeLayer(currentLayer);
	    			}
	        	}else{
	        		if(currentLayer == "image"){
		        		for(var i=0 ; i<this.imagesLayerIds.length; i++){
		        			var layer = this.map.getLayer(this.imagesLayerIds[i]);
	    					this.map.removeLayer(layer);
		        		}
		        		this.imagesLayerIds=[];
		        	}else if(currentLayer == "tencentmap"){
		        		for(var i=0 ; i<this.tencentLayerIds.length; i++){
		        			var layer = this.map.getLayer(this.tencentLayerIds[i]);
	    					this.map.removeLayer(layer);
		        		}
		        		this.tencentLayerIds=[];
		        	}else if(currentLayer == "tencentimagemap"){
		        		for(var i=0 ; i<this.tencentImagesLayerIds.length; i++){
		        			var layer = this.map.getLayer(this.tencentImagesLayerIds[i]);
	    					this.map.removeLayer(layer);
		        		}
		        		this.tencentImagesLayerIds=[];
		        	}
	        	}
    			var olderlayers,newlayers ="";
    			olderlayers =  this.map.layerIds.join(" ");
    			this._addAmapsLayer();//添加高德矢量底图
    			newlayers = this.map.layerIds.join(" ");
    			//根据添加影像地图前后图层的变化，来获取图层影像id
    			this.getAmapsLayerIds(olderlayers,newlayers);
	        },
	        handletencentLayer:function(currentLayer){
	        	debugger
	        	if(currentLayer instanceof Object){
	        		if(currentLayer.url){
	    				this.map.removeLayer(currentLayer);
	    			}
	        	}else{
	        		if(currentLayer == "image"){
		        		for(var i=0 ; i<this.imagesLayerIds.length; i++){
		        			var layer = this.map.getLayer(this.imagesLayerIds[i]);
	    					this.map.removeLayer(layer);
		        		}
		        		this.imagesLayerIds=[];
		        	}else if(currentLayer == "amap"){
		        		for(var i=0 ; i<this.amapsLayerIds.length; i++){
		        			var layer = this.map.getLayer(this.amapsLayerIds[i]);
	    					this.map.removeLayer(layer);
		        		}
		        		this.amapsLayerIds=[];
		        	}else if(currentLayer == "tencentimagemap"){
		        		for(var i=0 ; i<this.tencentImagesLayerIds.length; i++){
		        			var layer = this.map.getLayer(this.tencentImagesLayerIds[i]);
	    					this.map.removeLayer(layer);
		        		}
		        		this.tencentImagesLayerIds=[];
		        	}
	        	}
	        	var olderlayers,newlayers ="";
    			olderlayers =  this.map.layerIds.join(" ");
    			this._addTencentLayer();//添加高德矢量底图
    			newlayers = this.map.layerIds.join(" ");
    			//根据添加影像地图前后图层的变化，来获取图层影像id
    			this.getTencentLayerIds(olderlayers,newlayers);
	        },
	        handleTencentImagesLayer:function(currentLayer){
	        	if(currentLayer instanceof Object){
	        		if(currentLayer.url){
	    				this.map.removeLayer(currentLayer);
	    			}
	        	}else{
	        		if(currentLayer == "amap"){
		        		for(var i=0 ; i<this.amapsLayerIds.length; i++){
		        			var layer = this.map.getLayer(this.amapsLayerIds[i]);
	    					this.map.removeLayer(layer);
		        		}
		        		this.amapsLayerIds=[];
		        	}else if(currentLayer == "image"){
		        		for(var i=0 ; i<this.imagesLayerIds.length; i++){
		        			var layer = this.map.getLayer(this.imagesLayerIds[i]);
	    					this.map.removeLayer(layer);
		        		}
		        		this.imagesLayerIds=[];
		        	}else if(currentLayer == "tencentmap"){
		        		for(var i=0 ; i<this.tencentLayerIds.length; i++){
		        			var layer = this.map.getLayer(this.tencentLayerIds[i]);
	    					this.map.removeLayer(layer);
		        		}
		        		this.tencentLayerIds=[];
		        	}
	        	}
    			var olderlayers,newlayers ="";
    			olderlayers =  this.map.layerIds.join(" ");
    			this._addTencentImagesLayer();//添加影像图层
    			newlayers = this.map.layerIds.join(" ");
    			//根据添加影像地图前后图层的变化，来获取图层影像id
    			this.getTencentImagesLayerIds(olderlayers,newlayers);
	        },
	        _addImagesLayer: function(){
	        	require(["gistech/widgets/gaoDeLayer/GaoDeLayer","gistech/widgets/gaoDeLabelLayer/GaoDeLabelLayer"],
    					lang.hitch(this,function (GaoDeLayer,GaoDeLabelLayer) {
	        		//debugger
    				this.gaoDeLayer = new GaoDeLayer();
	        		this.gaoDeLayer._attrs={};
    				this.gaoDeLayer._attrs["name"]="image";
    				this.map.addLayer(this.gaoDeLayer,0);
    				this.gaoDeLabelLayer  = new GaoDeLabelLayer();
    				this.gaoDeLabelLayer._attrs={};
    				this.gaoDeLabelLayer._attrs["name"]="image";
    				this.map.addLayer(this.gaoDeLabelLayer,1);
    			}));
	        },
	        _addAmapsLayer: function(){
	        	require(["gistech/widgets/gaoDeLayer/GaoDeBaseMapLayer"],
    					lang.hitch(this,function (GaoDeBaseMapLayer) {
	        		//debugger
    				this.GaoDeBaseMapLayer  = new GaoDeBaseMapLayer();
    				this.map.addLayer(this.GaoDeBaseMapLayer,0);
    				this.GaoDeBaseMapLayer._attrs={};
    				this.GaoDeBaseMapLayer._attrs["name"]="amap";
    			}));
	        },
	        _addTencentLayer:function(){
	        	//debugger
	        	require(["gistech/widgets/tencentLayer/QQVectorLayer"],
    					lang.hitch(this,function(QQVectorLayer){
    						//debugger
    						this.TencentLayer = new QQVectorLayer();
    						this.map.addLayer(this.TencentLayer,0);
    						this.TencentLayer._attrs={};
    						this.TencentLayer._attrs["name"]="tencentmap";
    			}));
	        },
	        _addTencentImagesLayer: function(){
	        	require(["gistech/widgets/tencentLayer/QQImageLayer","gistech/widgets/tencentLabelLayer/QQLabelLayer"],
    					lang.hitch(this,function (QQImageLayer,QQLabelLayer) {
	        		//debugger
    				this.QQImageLayer = new QQImageLayer();
	        		this.QQImageLayer._attrs={};
    				this.QQImageLayer._attrs["name"]="tencentimagemap";
    				this.map.addLayer(this.QQImageLayer,0);
    				this.QQLabelLayer  = new QQLabelLayer();
    				this.QQLabelLayer._attrs={};
    				this.QQLabelLayer._attrs["name"]="tencentimagemap";
    				this.map.addLayer(this.QQLabelLayer,1);
    			}));
	        },
	        /**
	         * 获取影像地图图层的id(影像图层，文字图层)
	         */
	        getImagesLayerIds:function(olderlayers,newlayers){
	        	//debugger
	        	var ols = olderlayers.split(" ");
	        	var nls = newlayers.split(" ");
	        	for(var i=0;i<nls.length;i++){
					var flag = true; 
					for(var j=0; j<ols.length;j++){
						if(nls[i] == ols[j]){
							flag = false;
						}
					}
					if(flag){this.imagesLayerIds.push(nls[i])};
				}
	        },
	        /**
	         * 获取矢量地图图层的id(影像图层，文字图层)
	         */
	        getAmapsLayerIds:function(olderlayers,newlayers){
	        	//debugger
	        	var ols = olderlayers.split(" ");
	        	var nls = newlayers.split(" ");
	        	for(var i=0;i<nls.length;i++){
					var flag = true; 
					for(var j=0; j<ols.length;j++){
						if(nls[i] == ols[j]){
							flag = false;
						}
					}
					if(flag){this.amapsLayerIds.push(nls[i])};
				}
	        },
	        getTencentImagesLayerIds:function(olderlayers,newlayers){
	        	//debugger
	        	var ols = olderlayers.split(" ");
	        	var nls = newlayers.split(" ");
	        	for(var i=0;i<nls.length;i++){
					var flag = true; 
					for(var j=0; j<ols.length;j++){
						if(nls[i] == ols[j]){
							flag = false;
						}
					}
					if(flag){this.tencentImagesLayerIds.push(nls[i])};
				}
	        },
	        getTencentLayerIds:function(olderlayers,newlayers){
	        	//debugger
	        	var ols = olderlayers.split(" ");
	        	var nls = newlayers.split(" ");
	        	for(var i=0;i<nls.length;i++){
					var flag = true; 
					for(var j=0; j<ols.length;j++){
						if(nls[i] == ols[j]){
							flag = false;
						}
					}
					if(flag){this.tencentLayerIds.push(nls[i])};
				}
	        },
	        /**
	         * 改变地图切换后的样式
	         */
	        changeSelectedStyle:function(evt) {
	        	dojo.removeClass(dojo.query(".selected", this.domNode)[0], "selected");
				dojo.addClass(evt.target, "selected");
        		var l = this.map.getLevel();
        		if(l==17){
        		var mapname = this.getCurrentBaseMap();
        			if(mapname =="image" || mapname =="Warm" || mapname =="Cold" || mapname =="Gray" ){
        				this.map.setLevel(16);
        			}
        		}
	        },
	        /**
	         * 初始化时由basewidget从config的label取值直接替换模板中的{title}
	         * @param title
	         */
	        setTitle:function (title) {
	            this.headTitle.innerHTML = title;
	        },
	        /**
	         * 关闭窗口
	         */
	        closeDialog:function () {
	        	this.onClose();
	        },
	        /**
	         * 关闭中
	         */
	        onClose:function () {
                this._hidePopup();
	        },
	        /**
	         * 关闭窗口之前
	         */
	        onBeforeClose:function () {
	        },
	        /**
	         * 窗口尺寸改变的listener
	         */
	        onWindowResize:function () {
	            this._position();
	        },
	        /**
	         * 关闭窗口之后
	         */
	        onAfterClose:function () {
	        },
	        /**
	         * 定位，外层和内层的尖角分别定位
	         * @private
	         */
	        _position:function () {
	        	//debugger
	        	popupT=$(this.alignNode).offset().top;
	        	popupL=$(this.alignNode).offset().left - $(this.domNode).width()-25;
	            dojo.style(this.domNode, "top", popupT + "px");
	            dojo.style(this.domNode, "left", popupL + "px");
	        },
	        /**
	         * 隐藏窗口
	         * @param dom
	         * @private
	         */
	        _hidePopup:function (dom) {
	            if (this.hideWhenClickBody) {
	                if (dojo.style(this.domNode, "display") == "none") {
	                    //点击的是alignNode，显示popup
	                    if (dom == this.alignNode) {
	                        this.onShow();
	                    }
	                }else {
	                    //点击的是popup之外，隐藏popup
	                    if (!this.domNode.contains(dom)) {
	                        this.onHide();
	                    }
	                }
	            }
	        },
	        /**
	         * 显示窗口时
	         */
	        onShow:function () {
	        	//debugger
	            dojo.addClass(this.alignNode, "selected");
	            esri.show(this.domNode);
	        },
	        /**
	         * 隐藏窗口时
	         */
	        onHide:function () {
	            dojo.removeClass(this.alignNode, "selected");
	            esri.hide(this.domNode);
	        }
    });
});